import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        redirect: '/dashboard',
    },
    {
        path: '/login',
        component: () =>
            import(/* webpackChunkName: "user" */ '../views/Login.vue'),
    },
    {
        path: '/register',
        component: () =>
            import(/* webpackChunkName: "user" */ '../views/Register.vue'),
    },
    {
        path: '/',
        component: () =>
            import(/* webpackChunkName: "auth" */ '../views/auth/Index.vue'),
        children: [
            {
                path: 'dashboard',
                component: () =>
                    import(
                        /* webpackChunkName: "auth" */ '../views/auth/Dashboard.vue'
                    ),
            },
            {
                path: 'teacher/index',
                component: () =>
                    import(
                        /* webpackChunkName: "auth" */ '../views/auth/TeacherIndex.vue'
                    ),
            },
            {
                path: 'student/index',
                component: () =>
                    import(
                        /* webpackChunkName: "user" */ '../views/auth/StudentIndex.vue'
                    ),
            },
            {
                path: 'student/manage',
                component: () =>
                    import(
                        /* webpackChunkName: "auth" */ '../views/auth/StudentManage.vue'
                    ),
            },
            {
                path: 'score/manage',
                component: () =>
                    import(
                        /* webpackChunkName: "auth" */ '../views/auth/ScoreManage.vue'
                    ),
            },
            {
                path: 'profile',
                component: () =>
                    import(
                        /* webpackChunkName: "auth" */ '../views/auth/Profile.vue'
                    ),
            },
        ],
    },
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
});

router.beforeEach((to, from, next) => {
    if (to.path === '/login' || to.path === '/register') {
        next();
        return;
    }
    let token = window.sessionStorage.getItem('token');
    if (token) {
        next();
        return;
    }
    next('/login');
});

export default router;
